package ute.mvc.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ute.mvc.model.Question;
import ute.mvc.model.TestAndQuizz;
import ute.mvc.model.TestPart;

@Repository("testPartDAO")
public class TestPartDAOImpl implements TestPartDAO {
	@Autowired
	SessionFactory sessionFactory;

	public void addTestPart(TestPart testPart) {
		sessionFactory.getCurrentSession().save(testPart);
	}

	public void updateTestPart(TestPart testPart) {
		sessionFactory.getCurrentSession().merge(testPart);
	}

	public void deleteTestPart(TestPart testPart) {
		sessionFactory.getCurrentSession().delete(testPart);
	}

	// Vinh
	public String getMaxIdInTest(TestAndQuizz test) {
		// TODO Auto-generated method stub
		Criteria criteria = sessionFactory.getCurrentSession()
				.createCriteria(TestPart.class)
				.add(Restrictions.eq("testAndQuizz", test))
				.setProjection(Projections.max("testPartId"));
		String maxId = (String) criteria.uniqueResult();
		return maxId;
	}

	public TestPart getTestPartById(String id) {
		// TODO Auto-generated method stub
		return (TestPart) sessionFactory.getCurrentSession().get(
				TestPart.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<TestPart> getTestPartByTest(TestAndQuizz test) {
		// TODO Auto-generated method stub
		List<TestPart> list = sessionFactory.getCurrentSession()
				.createCriteria(TestPart.class)
				.add(Restrictions.eq("testAndQuizz", test))
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
		return list;
	}
}
